/**
 * Created by CY on 2017/12/18.
 */
(function(){

    var w = 38;
    /*var box ='<rect width="38" height="38" ><title></title></rect>';*/
    var colors ={
        disabledColor : "#f6faaa",  //#e4e4e4
        nodisabledColor : "#E6F598",  //#fff
        _goods_receipt_color : "#66C2A5",  //收货 #f39b16 #5E4FA2
        _deliver_goods_color : "#D53E4F",  //发货#2fb2a0 #66C2A5 #3288BD
    };

    var _param_ = {
        url : "",                // 数据源
        data : "",          // 当前时间
        //beforeLoad : null,       //数据加载成功后事件
        //afterLoad : null,       //数据加载成功后事件
        clickBox : null,        // 单元格点击事件
        //  BoxLoad: null,           //单元格加载事
        hoverBox : null ,         // 鼠标移动上去的事件
        width : null
    };
    var _datePlan_ = function( dom ){
        this.dom = dom;
    };
    var analyzeTime = function( time ){
        var times = time.split(":");

        return {
            h : +times[0] ,
            m : (+times[1]/60)
        };
    };
    var setUsableTime = function ( time , g_box, t ) {
        if($.type( time ) =="string"){
            var times =  time.split("-");
            var  startTime = analyzeTime(times[0]);
            var  endTime = analyzeTime(times[1]);
            var min_h  = startTime.h , max_h = endTime.h;
            var min_m  = startTime.m, max_m = endTime.m;
            if(min_h == max_h){
                var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
                rect.setAttribute("width",(w* ( max_m - min_m ) )+"px");
                rect.setAttribute("_key_",(max_h+"_user"));
                rect.setAttribute("height",w+"px");
                rect.setAttribute("fill",colors.nodisabledColor);
                rect.setAttribute("x", (min_h + min_m)*w);
                rect.setAttribute("y", t*w);
                $(rect).data("data",time);
                g_box.appendChild(rect);
            }else{
                for(var i = min_h; i < max_h +1; i++ ){
                    // g_box
                    var rect =  g_box.querySelector("[_key_='"+i+"']");
                    var num =1;
                    if(i ==  min_h){
                        rect.setAttribute("width", (w*min_m)+"px");
                        num = 1-min_m;
                        if(min_m == 0){
                            rect.remove();
                        }
                    }
                    else if(i ==  max_h){
                        rect.setAttribute("width", (w*(1-max_m) )+"px");
                        rect.setAttribute("x", (i+(max_m ==1 ? 0: max_m))*w);
                        num = max_m;
                        if(max_m == 1){
                            rect.remove();
                        }
                    }
                    else{
                        rect.remove();
                    }
                    if(num != 0 ){
                        var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
                        rect.setAttribute("width",(w*num)+"px");
                        rect.setAttribute("_key_",(i+"_user"));
                        rect.setAttribute("height",w+"px");
                        rect.setAttribute("fill",colors.nodisabledColor);
                        var x =  i ==  max_h ? i: (i+(num ==1 ? 0: (1-num) ));
                        rect.setAttribute("x", x*w);
                        rect.setAttribute("y", t*w);
                        $(rect).data("data",time);
                        g_box.appendChild(rect);
                    }

                }
            }

        }else{
            for(var i = 0; i < time.length; i++){
                setUsableTime ( time[i] , g_box, t);
            }
        }
        return g_box;
    };
    var setReserveTime = function ( data , g_box, t ) {
        if( data && data.length > 0 ) {
            for(var j = 0; j <data.length; j++) {
                var d = data[j];
                var color = d.type == 1 ? colors._goods_receipt_color : colors._deliver_goods_color;
                var type_k = d.type == 1 ? "_user_r" : "_user_s";
                var times =  d.time.split("-");
                var  startTime = analyzeTime(times[0]);
                var  endTime = analyzeTime(times[1]);
                var min_h  = startTime.h , max_h = endTime.h;
                var min_m  = startTime.m, max_m = endTime.m;
                if(min_h == max_h){
                    var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
                    rect.setAttribute("width",(w* ( max_m - min_m ) )+"px");
                    rect.setAttribute("_key_",(max_h+type_k));
                    rect.setAttribute("height",w+"px");
                    rect.setAttribute("fill",color);
                    rect.setAttribute("x", (min_h + min_m)*w);
                    rect.setAttribute("y", t*w);
                    $(rect).data("data",d);
                    g_box.appendChild(rect);
                }else{
                    for(var i = min_h; i < max_h +1; i++ ){
                        // g_box
                        var rect =  g_box.querySelector("[_key_='"+i+"_user']");
                        var num =1;
                        if(i ==  min_h){
                            rect.setAttribute("width", (w*min_m)+"px");
                            num = 1-min_m;
                            if(min_m == 0){
                                rect.remove();
                            }
                        }
                        else if(i ==  max_h){
                            rect.setAttribute("width", (w*(1-max_m) )+"px");
                            rect.setAttribute("x", (i+(max_m ==1 ? 0: max_m))*w);
                            num = max_m;
                            if(max_m == 1){
                                rect.remove();
                            }
                        }else{
                            rect.remove();
                        }
                        if(num != 0 ){
                            var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
                            rect.setAttribute("width",(w*num)+"px");
                            rect.setAttribute("_key_",(i+type_k));
                            rect.setAttribute("height",w+"px");
                            rect.setAttribute("fill", color);
                            var x =  i ==  max_h ? i: (i+(num ==1 ? 0: (1-num) ));
                            rect.setAttribute("x", x*w);
                            rect.setAttribute("y", t*w);
                            $(rect).data("data",d);
                            g_box.appendChild(rect);
                        }

                    }
                }


            }
        }
    };
    var loadData = function( data ){
        var svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
        svg.setAttribute('width',(w*24 + 60)+"px");
        svg.setAttribute('height',(110 + w*data.length )+"px");
        var x = 30, y = 100;
        var g_tools= document.createElementNS('http://www.w3.org/2000/svg','g');
        g_tools.setAttribute("transform","translate("+ x +",10)");
        svg.appendChild(g_tools);
        var _tools_ =0 ,label ={
            disabledColor : "不可预约",
            nodisabledColor : "空闲",
            _goods_receipt_color : "收货预约",  //收货
            _deliver_goods_color : "发货预约",  //发货
        };
        for(var o in colors){
            var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
            rect.setAttribute("width","30px");
            rect.setAttribute("height","10px");
            rect.setAttribute("fill",colors[o]);
            rect.setAttribute("x", 0 + _tools_*90 );
            rect.setAttribute("y", 10);
            g_tools.appendChild(rect);
            var text = document.createElementNS('http://www.w3.org/2000/svg','text');
            text.setAttribute("transform","translate("+(60+(_tools_*90))+",19)");
            text.setAttribute("font-family","sans-serif");
            text.setAttribute("font-size","10");
            text.setAttribute("text-anchor","middle");
            text.innerHTML = label[o];
            g_tools.appendChild(text);
            _tools_++;
        }
        var g_line= document.createElementNS('http://www.w3.org/2000/svg','g');
        g_line.setAttribute("transform","translate("+ x +",70)");
        svg.appendChild(g_line);
        for(var t = 0 ; t <24; t++){
            var line = document.createElementNS('http://www.w3.org/2000/svg','line');
            line.setAttribute("x1",t*w);
            line.setAttribute("y1",15);
            line.setAttribute("x2",(t+1)*w);
            line.setAttribute("y2",15);
            line.setAttribute("style","stroke:#666;stroke-width:2");
            g_line.appendChild(line);
        }
        for(var t = 0 ; t <25; t++){
            var circle = document.createElementNS('http://www.w3.org/2000/svg','circle');
            circle.setAttribute("cx",t*w);
            circle.setAttribute("cy",15);
            circle.setAttribute("r",5);
            circle.setAttribute("stroke","#3288BD");
            circle.setAttribute("stroke-width","2");
            circle.setAttribute("fill","#3288BD");
            var text = document.createElementNS('http://www.w3.org/2000/svg','text');
            text.setAttribute("transform","translate("+(t*w)+",5)");
            text.setAttribute("font-family","sans-serif");
            text.setAttribute("font-size","10");
            text.setAttribute("text-anchor","middle");
            text.innerHTML = t+":00";
            g_line.appendChild(text);
            g_line.appendChild(circle);
        }
        for(var i = 0; i < data.length; i++){
            var d =  data[i];
            var g = document.createElementNS('http://www.w3.org/2000/svg','g');
            g.setAttribute("transform","translate("+ x +","+ y+")");
            var text = document.createElementNS('http://www.w3.org/2000/svg','text');
            text.setAttribute("transform","translate(-10,"+( 20 + w*i)+")rotate(-90)");
            text.setAttribute("font-family","sans-serif");
            text.setAttribute("font-size","10");
            text.setAttribute("text-anchor","middle");
            text.innerHTML = d.title;
            g.appendChild(text);

            var g_box = document.createElementNS('http://www.w3.org/2000/svg','g');
            g_box.setAttribute("fill","none");
            g_box.setAttribute("stroke","#ccc");
            for(var t = 0 ; t <24; t++){
                var rect = document.createElementNS('http://www.w3.org/2000/svg','rect');
                rect.setAttribute("width",w+"px");
                rect.setAttribute("_key_",t);
                rect.setAttribute("height",w+"px");
                rect.setAttribute("fill",colors.disabledColor);
                rect.setAttribute("x", t*w);
                rect.setAttribute("y", i*w);
                /*    $(rect).data("data",d);*/
                g_box.appendChild(rect);
            }
            setUsableTime( d.usableTime, g_box ,i);
            setReserveTime( d.data, g_box ,i);
            g.appendChild(g_box);
            svg.appendChild(g);
        }
        this.dom.appendChild(svg);
        this._svg = svg;
    };
    var ajaxLoad = function( ){
        var p  = this.p, _this = this;


        $.ajax({
            url: p.url,
            data: p.data,
            async: false,
            success: function( data ){
                if(p.afterLoad &&  typeof p.afterLoad == 'function' ){
                    p.afterLoad.call(this, data);
                }
                data && (typeof data =="object") && data.length > 0 &&          loadData.call(_this, data);
            },
            error:function(){
                var  data =[
                    {
                        title:"月台",   //标题
                        usableTime :['09:00-12:00','13:00-16:00'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '10:10-11:20',
                            type:"1"
                        },{
                            id:"2", // 主键
                            text:"预约发货", //显示值
                            time: '13:30-15:20',
                            type:"2"
                        }]
                    },
                    {
                        title:"月台",   //标题
                        usableTime :['09:30-12:30','13:30-16:30'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '09:40-10:20',
                            type:"1"
                        }]
                    },
                    {
                        title:"月台",   //标题
                        usableTime :['00:00-09:00','16:00-23:00'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '16:50-22:50',
                            type:"2"
                        }]
                    },
                    {
                        title:"月台",   //标题
                        usableTime :['00:40-09:50','16:10-23:20'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '09:10-09:20',
                            type:"1"
                        }]
                    },
                    {
                        title:"月台",   //标题
                        usableTime :['08:00-18:00'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '10:10-11:20',
                            type:"2"
                        }]
                    },
                    {
                        title:"月台",   //标题
                        usableTime :['08:10-18:20'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '08:10- 11:20',
                            type:"1"
                        }]
                    },
                    {
                        title:"月台",   //标题
                        usableTime :['08:10-08:50'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '08:20- 08:40',
                            type:"1"
                        }]
                    }

                ];
                if( p.data.time =="2017-11-12"){
                    data = [ {
                        title:"月台",   //标题
                        usableTime :['08:10-18:50'], // 可用时间
                        data:[{
                            id:"1", // 主键
                            text:"预约收货", //显示值
                            time: '08:20- 08:40',
                            type:"1"
                        },{
                            id:"1", // 主键
                            text:"预约收货1", //显示值
                            time: '13:30- 15:40',
                            type:"1"
                        },{
                            id:"1", // 主键
                            text:"预约收货2", //显示值
                            time: '17:20- 18:00',
                            type:"2"
                        }]
                    }];
                }
                loadData.call(_this, data);
            }
        });
    };
    var setHoverClass = function(k, sign,direction){
        var name = direction ? (+k+direction)+sign : k+sign;
        var  dom = this.querySelector("[_key_='"+name+"']");

        if(dom ){
            dom.setAttribute("class","box_o");
            var  no_dom = this.querySelector("[_key_='"+(+k+direction)+"']");
            if(no_dom){
                return ;
            }
            if(direction){
                setHoverClass.call(this,+k+direction, sign,direction);
            }else{
                setHoverClass.call(this,k, sign,1);
                setHoverClass.call(this,k, sign,-1);
            }
        }else if( direction && ( sign.indexOf("_r") == -1 && sign.indexOf("_s") == -1 ) && -1<(+k) && (+k)<25 ){
            var  no_dom = this.querySelector("[_key_='"+(+k+direction)+"']");
            if(no_dom){
                return ;
            }
            setHoverClass.call(this,+k+direction, sign,direction);
        }
    };
    var bindFun = function(){
        var _this = this;
        this._svg.querySelectorAll("rect").forEach(function(e,i){
            e.onmouseover = function(){
                //console.dir(1);

                _this._svg.querySelectorAll("rect").forEach(function(e,i){
                    e.removeAttribute("class");
                });
                var k = this.getAttribute("_key_");
                var sign =k? k.indexOf("user_s") != -1  ? "_user_s" : (k.indexOf("user_r") != -1 ? "_user_r":(  k.indexOf("user") != -1  ? "_user" :"" ) ):false;

                sign && setHoverClass.call(this.parentNode, k.split("_")[0] , sign);
                var data = $(this).data("data");
                if($.type(data) == "object"){
                    data = data.text+"("+data.time+")";
                }
                if(data){
                    $(this).justToolsTip({
                        animation:"flipIn",
                        contents:data,
                        gravity:'bottom'
                    });
                    var hoverBox = _this.p.hoverBox;
                    hoverBox&& $.type(hoverBox) == 'function' && hoverBox.call(this, $(this).data("data"));
                }

            };
        });
        this._svg.querySelectorAll("rect").forEach(function(e,i){
            e.onclick = function(){
                var k = this.getAttribute("_key_");
                var sign = k ? k.indexOf("user_s") != -1  ? true : (k.indexOf("user_r") != -1 ? true:false ):false;
                if(sign){
                    var clickBox = _this.p.clickBox;
                    clickBox&& $.type(clickBox) == 'function' && clickBox.call(this, $(this).data("data"));
                }

            };
        });
        this._svg.onmouseout = function(){
            _this._svg.querySelectorAll("rect").forEach(function(e,i){
                e.removeAttribute("class");
            });
        }
    };
    var _init_ = function(){
        ajaxLoad.call(this);
        bindFun.call(this);
    };
    _datePlan_.prototype ={
        //初始化加载
        init : function( param ){

            this.p = $.extend(_param_ ,param );
            w = (this.p.width ? (this.p.width-60)/24 : w);
            _init_.call(this);
        },
        //重新加载
        reloadPlan : function(param){
            $(this._svg).remove();
            this.p = $.extend(this.p  ,param );
            w = (this.p.width ? (this.p.width-60)/24 : w);
            _init_.call(this);
        },

    };

    window.DatePlan = _datePlan_;
}());